<?php require_once(dirname(__FILE__) . '/inc/config.inc.php');
IsModelPriv('goodsorder');

require_once "function.php";
//初始化参数

$action = isset($action) ? $action : '';
$typeid = isset($typeid) ? $typeid : ''; // 提交类型
$device = isset($device) ? $device : ''; //设备类型
$repairid = isset($repairid) ? $repairid : ''; //任务类型
$manageid = isset($manageid) ? $manageid : ''; //执行人员
$beginTime = isset($beginTime) ? $beginTime : '';
$endTime = isset($endTime) ? $endTime : '';
$jindu = isset($jindu) ? $jindu : '';
$flag = isset($flag) ? $flag : '';
$keyword = isset($keyword) ? $keyword : ''; //关键词
//删除单条记录

if ($action == 'del') {
    $deltime = time();
    $dosql->ExecNoneQuery("UPDATE `#@__$tbname` SET is_delete='1', deltime='$deltime' WHERE id=$id");
}


//删除选中记录

if ($action == 'delall') {

    if ($ids != '') {

        //解析id,验证是否有删除权限
        $ids = explode(',', $ids);
        $idstr = '';
        foreach ($ids as $id) {

            $idstr .= $id . ',';

        }

        $idstr .= trim($idstr, ',');


        if ($idstr != '') {

            $deltime = time();

            $dosql->ExecNoneQuery("UPDATE `#@__$tbname` SET is_delete='1', deltime='$deltime' WHERE `id` IN ($idstr)");

        }

    }

}

?>

<div class="toolbarTab">
    <div class="tool2 row">
        <div class="col-md-1">
            <div class="tool1"><span class="btn btn-success" onclick="getFangAll()"><span
                            class="icon-list-alt icon-white"></span> 全部任务</span></div>
        </div>
        <div class="col-md-1">
            <div class="tool1"><span class="btn btn-danger" onclick="add_order()"><span
                            class="icon-list-alt icon-white"></span> 添加任务</span></div>
        </div>
    </div>
    <div class="row tool2">
        <div class="col-md-3">
            <div class="s-label"><span class="glyphicon glyphicon-wrench"></span> 服务类型：</div>
            <select class="form-control w150" name="typeid" id="typeid" onchange="getSelSearch()">
                <option value="-1">所有方式</option>
                <?php
                $dosql->Execute("SELECT * FROM `#@__cascadedata` WHERE `datagroup`='type' order by orderid ASC", 4);

                while ($row = $dosql->GetArray(4)) {

                    if ($typeid == $row['datavalue'])

                        $selected = 'selected="selected"';

                    else

                        $selected = '';

                    echo '<option value="' . $row['datavalue'] . '" ' . $selected . '>' . $row['dataname'] . '</option>';

                }

                ?>
            </select>
        </div>
        <div class="col-md-3">
            <div class="s-label"><span class="glyphicon glyphicon-blackboard"></span> 设备类型：</div>
            <select class="form-control w150" name="device" id="device" onchange="getSelSearch()">
                <option value="-1">设备类型</option>
                <?php

                $dosql->Execute("SELECT * FROM `#@__cascadedata` WHERE `datagroup`='device' order by orderid ASC", 10);

                while ($row = $dosql->GetArray(10)) {

                    if ($device == $row['datavalue'])

                        $selected = 'selected="selected"';

                    else

                        $selected = '';

                    echo '<option value="' . $row['datavalue'] . '" ' . $selected . '>' . $row['dataname'] . '</option>';

                }

                ?>
            </select>
        </div>
        <div class="col-md-3">
            <div class="input-group" style=" float:left;width: 240px; margin-left: -5px;">
                <input class="form-control date-picker" id="dateTimeRange"
                       value="<?php echo $beginTime ?>至<?php echo $endTime ?>" type="text">
                <span class="input-group-addon"> <i class="glyphicon glyphicon-calendar bigger-110"></i> </span>
                <input name="beginTime" id="beginTime" value="<?php echo $beginTime ?>" type="hidden">
                <input name="endTime" id="endTime" value="<?php echo $endTime ?>" type="hidden">
            </div>
            <a href="javascript:;" onclick="begin_end_time_clear();"
               style="float:left; margin-left:20px; height:34px; line-height:34px;">清除</a></div>
        <div class="col-md-3">
            <div class="s-label"><span class="glyphicon glyphicon-user"></span>客户名称：</div>
            <input type="text" class="form-control w150" name="keyword" id="keyword" title="输入客户名称进行搜索"
                   value="<?php echo $keyword; ?>">
            <a href="javascript:;" onclick="GetSearchOrder();" class="btn">搜索</a></div>

    </div>
    <div class="tool2 row">
        <div class="col-md-3">
            <div class="s-label"><span class="	glyphicon glyphicon-th-large"></span> 任务类型：</div>
            <select class="form-control w300" name="repairid" id="repairid" onchange="getSelSearch()">
                <option value="-1">所有</option>
                <?php
                $dosql->Execute("SELECT * FROM `#@__cascadedata` WHERE `datagroup`='renwu' order by orderid ASC", 10);
                while ($row = $dosql->GetArray(10)) {
                    if ($repairid == $row['datavalue'])
                        $selected = 'selected="selected"';
                    else
                        $selected = '';
                    echo '<option value="' . $row['datavalue'] . '" ' . $selected . '>' . $row['dataname'] . '</option>';

                }

                ?>
            </select>
        </div>
        <div class="col-md-3">
            <div class="s-label"><span class="	glyphicon glyphicon-ok-sign"></span> 执行人员：</div>
            <select class="form-control w150" name="manageid" id="manageid" onchange="getSelSearch()">
                <option value="-1">所有</option>
                <?php

                $dosql->Execute("SELECT * FROM  `#@__user` WHERE   level='3'     order by id asc", 10);

                while ($row = $dosql->GetArray(10)) {

                    if ($manageid == $row['id'])

                        $selected = 'selected="selected"';

                    else

                        $selected = '';

                    echo '<option value="' . $row['id'] . '" ' . $selected . '>' . $row['school'] . "-" . $row['truename'] . '</option>';

                }


                $dosql->Execute("SELECT * FROM  `#@__user` WHERE    level='5'    order by id asc", 10);

                while ($row = $dosql->GetArray(10)) {

                    if ($manageid == $row['id'])

                        $selected = 'selected="selected"';

                    else

                        $selected = '';

                    echo '<option value="' . $row['id'] . '" ' . $selected . '>' . $row['school'] . "-" . $row['truename'] . '</option>';

                }

                ?>
            </select>
        </div>
    </div>
</div>
</div>
<ul id="myTabs" class="nav nav-tabs">
    <li role="presentation" <?php if ($jindu == 'all' || $jindu == "") {
        echo 'class="active"';
    } ?> ><a href="javascript:;" onclick="getJindu('all')">所有状态</a></li>
    <li role="presentation" <?php if ($jindu == '99') {
        echo 'class="active"';
    } ?> ><a href="javascript:;" onclick="getJindu('99')">处理中</a></li>
    <?php
    $dosql->Execute("SELECT * FROM `#@__cascadedata` WHERE `datagroup`='jindu' order by orderid ASC", 5);
    while ($row = $dosql->GetArray(5)) {
        if ($jindu == $row['datavalue'])
            $selected = 'class="active"';
        else
            $selected = '';
        echo '<li  role="presentation" ' . $selected . '><a href="javascript:;" onclick="getJindu(' . $row['datavalue'] . ')">' . $row['dataname'] . '</a></li>';
    }
    ?>
</ul>
<input type="hidden" id="jindu" value="<?php echo $jindu; ?>">
<table width="100%" border="0" cellpadding="0" cellspacing="0" id="ajaxlist"
       class="dataTable table table-striped table-bordered">
    <tr height="50" align="left" class="head">
        <td width="3%">ID</td>
        <td width="10%">单位</td>
        <td width="10%">服务类型</td>
        <td width="15%">任务摘要</td>
        <td width="10%">执行人</td>
        <td width="7%">创建时间</td>
        <td width="3%">奖励</td>
        <td width="5%">进度</td>
        <td width="8%">距离</td>
        <td width="10%" class="endCol">操作</td>
    </tr>
    <?php
    //检查全局分页数
    if (empty($cfg_pagenum)) $cfg_pagenum = 20;
    //设置sql
    $sql_order = "SELECT f.*,t.classname as typename,j.dataname as jinduname,d.title as devicename FROM `#@__order` as f
		left join `#@__tasktype`  as t on t.id=f.apply_type  
		left join `#@__task`  as d on d.id=f.apply_device
		left join `#@__cascadedata`  as j on j.datavalue=f.jindu  
		WHERE  j.datagroup='jindu'  AND   f.is_delete='0'  ";
    if (!empty($keyword)) {
        $keyword = addslashes($keyword);
        $sql_order .= " AND  f.school LIKE '%$keyword%'";
    }
    if (!empty($typeid)) $sql_order .= " AND f.apply_type='$typeid'  ";
    if (!empty($repairid)) $sql_order .= " AND f.repairid='$repairid'  ";
    if (!empty($device)) $sql_order .= " AND f.apply_device='$device'  ";
    if (!empty($manageid)) $sql_order .= " AND FIND_IN_SET('$manageid',f.manageid)   ";
    if (!empty($beginTime) && !empty($endTime)) {
        $starttime = strtotime($beginTime);
        $endtime = strtotime($endTime) + 86400; //加一天
        $sql_order .= " AND f.post_time > " . $starttime . " AND f.post_time < " . $endtime;
    }
    if (intval($jindu) < 10 && $jindu != "all" && $jindu != "") {
        $sql_order .= " AND  f.jindu='" . $jindu . "'  ";
    }
    if ($jindu == "99") {
        $sql_order .= " AND f.jindu<5   AND f.jindu!=0   ";
    }

    $dopage->GetPage($sql_order);
    while ($row = $dosql->GetArray()) {


        //奖励金额
        if (intval($row['fee']) > 0) {
            $fee = '<span class="label label-danger">' . $row['fee'] . '</span>';
        } else {
            if ($row['jindu'] > 4) {
                $fee = '<span class="label label-success">免费</span>';
            } else {
                $fee = '';
            }
        }

        $type_name = "";
        if ($row['apply_type'] == '1') {
            $type_name = '<span class="label label-danger">' . $row['typename'] . '</span>';
        } elseif ($row['apply_type'] == '2') {
            $type_name = '<span class="label label-success">' . $row['typename'] . '</span>';
        } else {
            $type_name = $row['typename'];
        }

        //工单是否超时
        //超时 高亮标记
        $tr_color = "";
        $is_timeout = 'false';
        if ($row['jindu'] == '4') {
            $row_order = $dosql->GetOne("SELECT *  FROM  `#@__order_log`  where   orderid='" . $row['id'] . "'   AND jindu='4'  order by id desc   ");
            if (is_array($row_order) && isset($row_order['op_time'])) {
                $last_time = $row_order['op_time'];
                if (time() - $last_time > 86400) {
                    $tr_color = "danger";
                    $is_timeout = 'true';
                }
            }
        }

        $qiang_str = "";
        if ($row['mode'] == 'q') {
            $qiang_str = '<span class="label label-success">抢单</span>';
        }

        ?>
        <tr align="left" class="<?php echo $tr_color; ?>">
            <td><?php echo $row['id']; ?></td>
            <td><?php echo $row['school']; ?></td>
            <td><?php echo $type_name . "   " . $row['devicename']; ?></td>
            <td><?php echo $qiang_str . "   " . $row['content']; ?></td>
            <td>
                <?php
                if (!empty($row['manageid'])) {
                    $m_str = $row['manageid'];
                    $m_arr = explode(",", $m_str);
                    foreach ($m_arr as $key => $val) {
                        echo ' <i class="glyphicon glyphicon-user"></i>      ' . getManage($val);
                    }
                }

                ?>

            </td>
            <td class="number"><?php echo GetDateTime($row['post_time']); ?><?php if (empty($row['poster'])) {
                    echo '<i class="glyphicon glyphicon-qrcode"></i>';
                }; ?> </td>
            <td><?php echo $fee; ?></td>
            <td><?php
                echo $row['jinduname'];
                if ($is_timeout == 'true') {
                    echo '<span class="label label-danger">超时</span>';
                }
                ?>
            </td>
            <td><?php
                //获取签到数据
                $order_id = $row['id'];
                $row_q = $dosql->GetOne("SELECT * FROM `#@__order_log` WHERE `orderid`='$order_id'  and qiandao='true' ");
                if (is_array($row_q) && isset($row_q['id'])) {


                    if ($row_q['latitude'] != "" && $row['latitude'] != "") {
                        $dd = distance($row_q['longitude'], $row_q['latitude'], $row['longitude'], $row['latitude']);
                        if ($row['poster'] != "") {
                            echo "公司->签到：" . $dd . " 米<br/>";
                        } else {
                            echo "报修->签到：" . $dd . " 米<br/>";
                        }
                        echo "<a href='javascript:;' onclick=daohang(" . $order_id . ")>接->签导航距离" . ($row['driving_distance'] / 1000) . "公里</a>";

                    }

                    if ($row_q['latitude'] != "" && $row['latitude2'] != "") {
                        $dd = distance($row_q['longitude'], $row_q['latitude'], $row['longitude2'], $row['latitude2']);
                        if (intval($dd) > 1000) {
                            echo "<b class='red'>签到->完修：" . $dd . " 米</b><br>";
                        } else {
                            echo "签到->完修：" . $dd . "米<br/>";
                        }

                    }
                    if ($row['latitude'] != "" && $row['latitude2'] != "") {
                        $dd = distance($cfg_longitude, $cfg_latitude, $row['longitude2'], $row['latitude2']);
                        echo "公司->完修：" . $dd . "米";


                    }
                }

                ?>
            </td>
            <td class="action endCol">
                <button type="button" class="btn btn-success" onclick="dongdanshow('<?php echo $row['id'] ?>')"><i
                            class="glyphicon glyphicon-align-left" aria-hidden="true"></i>管理
                </button>
                <?php if ($row['jindu'] < 5 && $row['jindu'] > 0) { ?>
                    <button type="button" class="btn btn-danger" onclick="stoporder('<?php echo $row['id'] ?>')"><i
                                class="	glyphicon glyphicon-ban-circle" aria-hidden="true"></i>中止
                    </button>  <?php } ?>
                <?php if ($row['jindu'] < 4 && $row['jindu'] > 0) { ?>
                    <button type="button"  id="m_<?php echo $row['id']; ?>"  data-index="<?php echo $row['school']; ?>"
                            class="btn btn-default" onclick="delM('<?php echo $row['id'] ?>')"><i
                                class="glyphicon glyphicon-trash" aria-hidden="true"></i>删除</button> <?php } ?>
                <?php if ($row['jindu'] == 5 || $row['jindu'] == 6  ) { ?>
                    <button type="button" class="btn btn-danger" onclick="jifen('<?php echo $row['id'] ?>')"><i
                                class="	glyphicon  glyphicon-usd " aria-hidden="true"></i>奖励</button>  <?php } ?>
            </td>
        </tr>
        <?php

    }

    ?>
</table>
<?php


//判断无记录样式

if ($dosql->GetTotalRow() == 0) {

    echo '<div class="dataEmpty">暂时没有相关的记录</div>';

} ?>
<div class="page"> <?php echo $dopage->AjaxOrderPage(); ?> </div>
<?php

//审核销售

if ($cfg_adminlevel == 1) {


    ?>
    <?php

}

//判断是否启用快捷工具栏

if ($cfg_quicktool == 'Y' && $cfg_adminlevel == 1) {

    ?>
    <div class="quickToolbar">
        <div class="qiuckWarp">
            <div class="quickArea"><?php echo $dopage->AjaxPageSmall(); ?> </div>
            <div class="quickAreaBg"></div>
        </div>
    </div>
    <?php

}


?>
<script type="text/javascript">
    $(function () {
        $('#dateTimeRange').daterangepicker({
            applyClass: 'btn-sm btn-success',
            cancelClass: 'btn-sm btn-default',
            locale: {
                applyLabel: '确认',
                cancelLabel: '取消',
                fromLabel: '起始时间',
                toLabel: '结束时间',
                customRangeLabel: '自定义',
                firstDay: 1
            },
            ranges: {
                //'最近1小时': [moment().subtract('hours',1), moment()],
                '今日': [moment().startOf('day'), moment()],
                '昨日': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],
                '最近7日': [moment().subtract('days', 6), moment()],
                '最近30日': [moment().subtract('days', 29), moment()],
                '本月': [moment().startOf("month"), moment().endOf("month")],
                '上个月': [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")]
            },
            opens: 'right',	// 日期选择框的弹出位置
            separator: ' 至 ',
            showWeekNumbers: true,		// 是否显示第几周


            //timePicker: true,
            //timePickerIncrement : 10,	// 时间的增量，单位为分钟
            //timePicker12Hour : false,	// 是否使用12小时制来显示时间


            maxDate:<?php echo date("Y-m-d", time())?>,			// 最大时间
            format: 'YYYY-MM-DD'

        }, function (start, end, label) { // 格式化日期显示框
            $('#beginTime').val(start.format('YYYY-MM-DD'));
            $('#endTime').val(end.format('YYYY-MM-DD'));
            getSelSearch();

        })
            .next().on('click', function () {
            $(this).prev().focus();
        });
    });

    /**
     * 清除时间
     */
    function begin_end_time_clear() {
        $('#dateTimeRange').val('');
        $('#beginTime').val('');
        $('#endTime').val('');
    }


    function delM(id) {

        var id_name = $("#m_" + id).data("index");
        var del_str = "您确定要删除    " + id_name + "   吗, 确认删除?";
        layer.confirm(del_str, function () {
            //操作
            $.ajax({
                type: 'POST',
                url: "op.php",
                data: {id: id, op: 'delM'},
                dataType: 'JSON',
                success: function (result) {
                    console.log(result);
                    if (result.errno == 0) {
                        console.log(result.msg);
                        if (result.msg === "ok") {
                            layer.msg('删除成功');
                            window.location.reload();
                        } else {
                            layer.msg(result.err_msg);
                        }
                    }
                }
            });
        }, function () {
            //取消操作
        });

    }


</script>
<style>
    .nav-tabs > li.active > a {
        color: #fff !important;
        background-color: #337ab7 !important;
    }
</style>
<script>

    $('#myTabs a').click(function (e) {
        e.preventDefault()
        $(this).tab('show')
    })
</script>